<template>
  <div class="users">
    <!-- 面包屑组件 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索框: input组件 -->
    <el-input placeholder="请输入内容" v-model="searchVal" class="search-input">
      <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
    </el-input>
    <el-button type="primary" plain @click="handleAddUser">添加用户</el-button>

    <!-- table组件 -->
    <el-table v-loading="loading" class="mt-15" :data="userList" border style="width: 100%">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="address" label="切换状态">
        <template slot-scope="scope">
          <el-switch
            :disabled="scope.row.username==='admin'"
            v-model="scope.row.mg_state"
            @change="handleChangeState(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)"></el-button>
          <el-button type="warning" icon="el-icon-check" circle @click="handleGrant(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      class="mt-15 page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="1"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加弹框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible" :before-close="closeDialog">
      <el-form :model="addForm" :rules="myrules" ref="addRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelselector('add')">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible" >
      <el-form :model="editForm" :rules="myrules" ref="editRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editForm.username" auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelselector('edit')">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 授权弹框 -->
    <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
      <el-form :model="grantForm" :rules="myrules" ref="grantRef">
        <el-form-item label="当前的用户" :label-width="formLabelWidth">
          <el-input v-model="grantForm.username" auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="请选择角色" :label-width="formLabelWidth">
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmGrant">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getUserList, addUser, deleteUser, changeState, editUser, grantUserRole, getRoles } from '@/api'
export default {
  created () {
    this.initTable()
  },
  data () {
    return {
      roleList: [],
      selectRoleId: '', // 选中的角色id
      loading: true,
      searchVal: '',
      userList: [],
      pagesize: 4, // 每页多少条，默认2条
      pagenum: 1, // 当前页面，默认第一页
      addDialogFormVisible: false,
      addForm: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      editDialogFormVisible: false,
      editForm: {
        id: '',
        username: '',
        mobile: '',
        email: ''
      },
      grantDialogFormVisible: false,
      grantForm: {
        username: '',
        id: -1
      },
      formLabelWidth: '120px',
      total: 0,
      myrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  methods: {
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.initTable()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagenum = val
      this.initTable()
    },
    // 初始化列表:
    initTable () {
      this.loading = true
      getUserList({
        query: this.searchVal,
        pagenum: this.pagenum,
        pagesize: this.pagesize

      }).then(res => {
        this.userList = res.data.users
        this.total = res.data.total
        this.loading = false
      })
    },
    handleSearch () {
      this.initTable()
      this.searchVal = ''
    },
    // 添加用户:
    handleAddUser () {
      this.addDialogFormVisible = true
    },
    confirmAdd () {
      this.$refs.addRef.validate(isPass => {
        if (isPass) {
          addUser(this.addForm).then(res => {
            if (res.meta.status === 201) {
              this.$message.success('添加用户成功')
              this.addDialogFormVisible = false
              // 清空表单
              this.addForm = {}
              // 刷新数据
              this.initTable()
            } else {
              this.$message.error(res.meta.msg)
            }
          })
        } else {
          // 弹错误的提示信息
          this.$message.error('请正确填写表单信息')
        }
      })
    },
    handleDelete (row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteUser(row.id).then(res => {
            if (res.meta.status === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.initTable()
            } else {
              this.$message.error(res.meta.meg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleChangeState (row) {
      changeState(row.id, row.mg_state).then(res => {
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          this.initTable()
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    cancelselector (selector) {
      this[selector + 'DialogFormVisible'] = false
      this[selector + 'Form'] = {}
      this.$refs[selector + 'Ref'].clearValidate()
    },
    closeDialog (done) {
      this.addForm = {}
      this.$refs.addRef.clearValidate()
      done()
    },
    handleEdit (row) {
      this.editDialogFormVisible = true
      // 给编辑弹框的表单赋值:
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.mobile = row.mobile
      this.editForm.email = row.email
    },
    confirmEdit () {
      this.$refs.editRef.validate(isPass => {
        if (isPass) {
          editUser(this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }).then(res => {
            if (res.meta.status === 200) {
              this.$message.success(res.meta.msg)
              this.editDialogFormVisible = false
              this.initTable()
            } else {
              this.$message.error(res.meta.msg)
            }
          })
        } else {
          this.$message.error('请输入正确的表单信息')
        }
      })
    },
    handleGrant (row) {
      this.grantForm.username = row.username
      this.grantForm.id = row.id
      this.selectRoleId = row.role_name
      this.grantDialogFormVisible = true
      getRoles()
        .then(res => {
          this.roleList = res.data
        })
    },
    confirmGrant () {
      if (typeof this.selectRoleId === 'string') {
        this.grantDialogFormVisible = false
        return false
      }
      grantUserRole(this.grantForm.id, this.selectRoleId)
        .then(res => {
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg)
            this.grantDialogFormVisible = false
            this.initTable()
          } else {
            this.$message.error(res.meta.msg)
          }
        })
    }
  }
}
</script>
<style lang="scss" scoped>
  .search-input {
    width: 300px;
    margin-right: 5px;
  }
</style>
